<?php

class mgPicasaStorage {
    
    var $sizes = array();
    var $albumIds = array();
    
    var $original_images = array();
    
    var $user = '';
    var $pass = '';
    
    var $gp   = null;
    
    function __construct() {
        $this->sizes = get_option('mgps_thumb_sizes');
        
        $this->user  = get_option('mgps_picasa_user');
        $this->pass  = get_option('mgps_picasa_pass');
    }
    
    function doit($content)
    {
        global $post_ID;
        
        if (!$this->original_images_get($content)) return $content;
        if (empty($this->user) || empty($this->pass)) return $content;
        
        $local_original_images = array();
        foreach($this->original_images as $image) {
            $local_original_images[] = $this->save2local($image);
        }
        
        if (empty($this->gp)) $this->gp();
        
        
        // 为文章的第一张图片制作缩略图，并直接上传
        if (is_array($this->sizes) && !empty($this->sizes)) {
            require_once MGPS_PLUGINDIR.'/phpthumb/ThumbLib.inc.php';
            foreach($this->sizes as $size) {
                list($width, $height) = explode('x', $size);
                $thumbfile = $this->thumb($this->original_images[0], $width, $height);
                $uf = $this->upload("{$width}x{$height}", $thumbfile);
                
                // 保存到meta
                add_post_meta($post_ID, "thumb_{$width}x{$height}", $uf, true)
                or
                update_post_meta($post_ID, "thumb_{$width}x{$height}", $uf);
            }
        }
        
        // 上传原始的图片
        $uploaded = array();
        foreach($local_original_images as $image) {
            if (empty($image)) {
                $uploaded[] = '';
            }else {
                $uploaded[] = $this->upload('original', $image);
            }
        }
        
        // 将第一张图片地址保存到Meta中
        add_post_meta($post_ID, "original", $uploaded[0], true)
        or
        update_post_meta($post_ID, "original", $uploaded[0]);
        
        // 替换原始图片地址为新图片地址
        foreach($this->original_images as $id => $old) {
            if (empty($uploaded[$id])) return false;
            if ($gpicasa_width = get_option('mgps_thumbwidth_in_content')) {
            	$new = mgps_gthumb($uploaded[$id], $gpicasa_width);
            }else {
                $new = $uploaded[$id];
            }
            $content = str_replace($old, $new, $content);
        }
        return $content;
    }
    
    /**
     * 获取非Picasa存储的图片地址列表
     *
     * @param string $content
     * @return array
     */
    function original_images_get($content)
    {
        $content = stripslashes($content);
        
        //$pattern = '/http:\/\/(?!lh\d+?\.ggpht\.com)\S+\.(?:jpg|gif|png)/i';
        $pattern = '/<img[\s\S]+?(?:"|\')(http:\/\/(?!lh\d+?\.ggpht\.com)\S+)(?:"|\')[\s\S]*>/i';
        preg_match_all($pattern, $content, $matches);
        if (empty($matches[1])) return false;
        $this->original_images = $matches[1];
        return true;
    }
    
    // 保存远程图片到本地临时文件
    function save2local($filename)
    {
        $tmpfile = tempnam(sys_get_temp_dir(), 'mgps_');
        file_put_contents($tmpfile, file_get_contents($filename));
        return $tmpfile;
    }
    
    // 生成缩略图
    function thumb($original_image, $width, $height)
    {
        $tmpfile = tempnam(sys_get_temp_dir(), 'mgps_');
        $thumb = PhpThumbFactory::create($original_image);
        $thumb->adaptiveResize($width, $height);
        $thumb->save($tmpfile);
        
        return $tmpfile;
    }
    
    // 登录Google，获得操作实例
    function gp()
    {
	    require_once 'Zend/Loader.php';
        Zend_Loader::loadClass('Zend_Gdata_Photos');
        Zend_Loader::loadClass('Zend_Gdata_Photos_AlbumQuery');
        Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
        Zend_Loader::loadClass('Zend_Gdata_AuthSub');

        $serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;
        $client = Zend_Gdata_ClientLogin::getHttpClient($this->user, $this->pass, $serviceName);
        $this->gp = new Zend_Gdata_Photos($client, "Google-DevelopersGuide-1.0");
    }
    
    // 上传多个文件到picasa，并需要指定相册
    function upload($albumName, $image)
    {
        global $post_ID;
        
        if (empty($this->gp)) $this->gp();
        
        $username = $this->user;
        $photoCaption = $photoName = $photoTags = "postID_{$post_ID}";
        
        $fd = $this->gp->newMediaFileSource($image);
        $fd->setContentType("image/jpeg");
        
        
        // Create a PhotoEntry
        $photoEntry = new Zend_Gdata_Photos_PhotoEntry();
        
        $photoEntry->setMediaSource($fd);
        $photoEntry->setTitle($this->gp->newTitle($photoName));
        $photoEntry->setSummary($this->gp->newSummary($photoCaption));
        
        // add some tags
        $keywords = new Zend_Gdata_Media_Extension_MediaKeywords();
        $keywords->setText($photoTags);
        $photoEntry->mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup();
        $photoEntry->mediaGroup->keywords = $keywords;
        
        // We use the AlbumQuery class to generate the URL for the album
        $albumQuery = new Zend_Gdata_Photos_AlbumQuery();
        $albumQuery->setUser($username);
        $albumQuery->setAlbumName($albumName);
        
        $insertedEntry = $this->gp->insertPhotoEntry($photoEntry, $albumQuery->getQueryUrl());
        
        $mediaContentArray = $insertedEntry->getMediaGroup()->getContent();
        return $mediaContentArray[0]->getUrl();
    }
    
    function createAlbumByName($albumName)
    {
        if (empty($this->gp)) $this->gp();
        
    	$query = new Zend_Gdata_Photos_AlbumQuery();
    	$query->setUser($this->user);
    	$query->setAlbumName($albumName);
    	
    	try {
    	    $albumEntry = $this->gp->getAlbumEntry($query);
            return preg_replace('/.*albumid\/(\d+)/', '$1', $albumEntry->id->text);
    	}catch (Zend_Gdata_App_Exception $e) {
    	    $entry = new Zend_Gdata_Photos_AlbumEntry();
            $entry->setTitle($this->gp->newTitle($albumName));
            $entry->setGphotoAccess($this->gp->newAccess("public"));
            $insertedEntry = $this->gp->insertAlbumEntry($entry);
            return preg_replace('/.*albumid\/(\d+)/', '$1', $insertedEntry->id->text);
    	}
    }
}

?>